package com.etrans.web.gps.business.Index.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.Index.domain.IndexInfo;
import com.etrans.web.gps.business.Index.service.IndexService;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.timer.LocalCache;
import com.etrans.web.gps.util.AlarmKindUtil;
import com.etrans.web.gps.util.DateUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

@Controller
@RequestMapping("/index/")
public class IndexController extends BaseController {

	@Autowired
	private IndexService indexService;




	@Autowired
	private AlarmKindUtil alarmKindUtil;

	/**
	 * 跳转到首页
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("toIndex.html")
	public ModelAndView indexForProvince() {
		ModelAndView mv = new ModelAndView();
		SysUser user = getSysUser();
		mv.addObject("username", user.getLogin_name());
		mv.setViewName("views/business/index/index");
		return mv;

	}

	/**
	 * 平台概况
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getIndexInfo.html")
	public Map<String, Object> getIndexInfo() {
		SysUser user = getSysUser();
		Map<String, Object> data;
		Map<String, Object> result = new HashMap<>();
		try {
			data = indexService.getIndexInfo(user.getArea_id());

			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("fullID", String.format("%08d", user.getArea_id()));
			List<HashMap<String, Object>> vList = indexService.getNetVehicle(params);
			String[] keys = new String[vList.size()];
			// 组装Keys=车牌号码+车牌颜色Id
			for (int i = 0; i < vList.size(); i++) {
				String vehicleNo = vList.get(i).get("vehicleNo").toString();
				String vehicleColor = vList.get(i).get("vehicleColor").toString();
				keys[i] = String.format("%s_%s", vehicleNo, vehicleColor);
			}

			Set<String> onlineList = LocalCache.onlineVehicles.get("online");
			int onLineCount = 0;
			int netCount =vList.size();
			if (onlineList !=null && onlineList.size() > 0) {
				for(String key :keys){
					if(onlineList.contains(key)){
						onLineCount++;
					}
				}
				data.put("online", onLineCount);
			}
			if (netCount != 0) {
				data.put("onLineRate", onLineCount / (float) netCount * 100);
			} else {
				data.put("onLineRate", 0.0);
			}
			String startTime = DateUtil.getDayStart(new Date());
			Date queryDate = DateUtil.getISODate(startTime);
			BasicDBObject dbObject = new BasicDBObject("$gte",queryDate );
			BasicDBObject alarmResult = new BasicDBObject("alarm_time",dbObject);
			alarmResult.put("history", new BasicDBObject("$ne",null));
		//	List<Integer> alarmList = alarmKindUtil.getAlarmKindList();
		//	result.put("alarm_type", new BasicDBObject("$in",alarmList));
			long alarmDealCount = MGTemplete.findCount("egov", "alarm_result", alarmResult);
			String alarmDate = DateUtil.getDateToString(new Date(), "yyMMdd");
		//	BasicDBObject alarmInfo = new BasicDBObject("alarm_type", new BasicDBObject("$in",alarmList));
			long alarmAllCount = MGTemplete.findAllCount("egov", "alarm_info_" + alarmDate);
			if (alarmAllCount != 0) {
				double dealRate = alarmDealCount / (float) alarmAllCount * 100;
				data.put("dealRate", dealRate);
			} else {
				data.put("dealRate", 0.0);
			}
			result.put("code", "10001");
			result.put("data", data);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", "10001");
			result.put("msg", "程序出错！");
			return result;
		}
	}

	/**
	 * 平台接入状态
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getPlatformStatus.html")
	public Map<String, Object> getPlatformStatus() {
		SysUser user = getSysUser();
		List<Map<String, Object>> temp = new ArrayList<>();
		Map<String, Object> result = new HashMap<>();
		List<Map<String, Object>> list;
		try {
			list = indexService.getPlatformStatus(user.getArea_id());
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> addMap = list.get(i);
				HashMap<String, Object> whereParam = new HashMap<>();
				whereParam.put("gnsscenter_id", list.get(i).get("gnss_centerid"));
				HashMap<String, Object> sortMap = new HashMap<>();
				sortMap.put("time", -1);
				temp = MGTemplete.find("egov", "sub_link_log", whereParam, sortMap);
				if (!temp.isEmpty() && temp.size() != 0) {
					// 取最新的一条数据
					String mainLinkState = String.valueOf(temp.get(0).get("main_link_state"));
					String subLinkState = String.valueOf(temp.get(0).get("sub_link_state"));
					if(!mainLinkState.equals("null") && !subLinkState.equals("null")){
						int mainLink = Integer.valueOf(mainLinkState); // 主链路
						int subLink = Integer.valueOf(subLinkState);// 下级链路
						
						// 当两条链路都为0时为联通状态，0:连通, 1:断开
						if (mainLink == subLink && subLink == 0) {
							addMap.put("status", true);
						} else {
							addMap.put("status", false);
						}
					}
				}else{
					addMap.put("status", false);
				}
			}
			result.put("code", 10001);
			result.put("data", list);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 10002);
			result.put("msg", "获取失败！");
			return result;
		}

	}

	/**
	 * 车辆统计
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getStatisticsByArea.html")
	public Map<String, Object> getStatisticsByArea() {
		Map<String, Object> result = new HashMap<>();
		Map<String,Object> map = new HashMap<String,Object>();
		SysUser user = getSysUser();
		map.put("area_id", user.getArea_id());
		map.put("FullID",user.getFullID());
		List<IndexInfo> list;
		try {
			list = indexService.getAreaInfo(map);
			for (IndexInfo info : list) {
				info = indexService.getStatisticsByArea(info, user.getArea_id());
				List<String> vehList = indexService.getVehicleByArea(info, user.getArea_id());
				info.setNetVehicleCount(vehList.size());
				//将key转为数组
				String[] keys = vehList.toArray(new String[vehList.size()]);
				int onLineCount = 0;
				Set<String> onlineList = LocalCache.onlineVehicles.get("online");
				if (onlineList !=null && onlineList.size() > 0) {					
					for(String key :keys){
						if(onlineList.contains(key)){
							onLineCount++;
						}
					}
				}
				// 取在线率=在线数/入网车辆数
				if (info.getNetVehicleCount() != 0) {
					info.setOnlineRate((onLineCount / (float) info.getNetVehicleCount()) * 100);
				} else {
					info.setOnlineRate(0.0);
				}
			}
			result.put("code", 10001);
			result.put("data", list);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 10001);
			result.put("msg", "程序报错！");
			return result;

		}

	}

	/**
	 * 行业信息统计
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getStatisticsByTrade.html")
	public Map<String, Object> getStatisticsByTrade() {
		Map<String, Object> result = new HashMap<>();
		SysUser user = getSysUser();
		List<IndexInfo> list;
		try {
			list = indexService.getTradeInfo();
			for (IndexInfo info : list) {
				List<Map<String, Object>> vehListAll = indexService.getVehicleByTradeAll(info, user.getArea_id());
				List<Map<String, Object>> vehList = indexService.getVehicleByTrade(info, user.getArea_id());
				info.setVehicleAll(vehListAll.size());
				info.setNetVehicleCount(vehList.size());
				String[] keys = new String[vehList.size()];
				// 组装Keys=车牌号码+车牌颜色Id
				for (int i = 0; i < vehList.size(); i++) {
					String vehicleNo = vehList.get(i).get("vehicleNo").toString();
					String vehicleColor = vehList.get(i).get("vehicleColor").toString();
					keys[i] = String.format("%s_%s", vehicleNo, vehicleColor);
				}
				// 根据车辆查询在线车辆
				int onLineCount = 0;
				Set<String> onlineList = LocalCache.onlineVehicles.get("online");
				if (onlineList !=null && onlineList.size() > 0) {				
					for(String key :keys){
						if(onlineList.contains(key)){
							onLineCount++;
						}
					}
				}
				
				info.setOnlineCount(onLineCount);
				// 取在线率=在线数/入网车辆数
				if (info.getNetVehicleCount() != 0) {
					info.setOnlineRate((onLineCount / (float) info.getNetVehicleCount()) * 100);
				} else {
					info.setOnlineRate(0.0);
				}
			}
			result.put("code", 10001);
			result.put("data", list);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 10002);
			result.put("msg", "程序出错！");
			return result;
		}

	}

	/**
	 * 今日报警分析
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("getAlarmStatistics.html")
	public Map<String, Object> getAlarmStatistics() {
		Map<String, Object> result = new HashMap<>();
		try {
			// 左边柱状图
			Integer[] alarmTypes = alarmKindUtil.getAlarmKindInt(); // 获取报警类型
			List<Map<String, Object>> list = new ArrayList<>();
			for (int i = 0; i < alarmTypes.length; i++) {
				Map<String, Object> res = new HashMap<>();
				List<Bson> bson = new ArrayList<>();
				//提取字段筛选报警类型
				DBObject projectFiled = new BasicDBObject("_id", "$_id");
				projectFiled.put("bizId", "$biz_id");
				projectFiled.put("alarm", "$alarms."+alarmTypes[i]+".alarm_type");
				projectFiled.put("alarmtime", "$alarms."+alarmTypes[i]+".alarm_time");
				Bson project = new BasicDBObject("$project", projectFiled);
				
				// 取当天实时报警
				String startTime = DateUtil.getDayStart(new Date());
			//	String startTime = DateUtil.getDateTimeString(new Date(), "yyyy-MM-dd")+" 08:00:00";
				// 匹配报警类型
				DBObject matchField = new BasicDBObject("alarmtime",new BasicDBObject("$gte", DateUtil.getDate(startTime)));
				Bson match = new BasicDBObject("$match", matchField);
				// 根据车牌号和颜色分组
				DBObject groupFields = new BasicDBObject("_id", "$bizId");
				Bson group = new BasicDBObject("$group", groupFields);
				// 统计分组后的报警数
				DBObject groupField2 = new BasicDBObject("_id", "$_id.bizId");
				groupField2.put("count", new BasicDBObject("$sum", 1));
				Bson group2 = new BasicDBObject("$group", groupField2);
				// 先匹配后分组再统计
				bson.add(project);
				bson.add(match);
				bson.add(group);
				bson.add(group2);

				List<Object> obj = MGTemplete.aggregate("egov", "alarm_info_realtime", bson);
				if (obj.size() != 0) {
					Map<String, Object> q = (Map<String, Object>) obj.get(0);
					res.put("alarmType", alarmTypes[i]);
					res.put("vehicleCount", q.get("count"));
				} else {
					res.put("alarmType", alarmTypes[i]);
					res.put("vehicleCount", 0);
				}

				// 右边折线图
				bson = new ArrayList<>();
				// 根据小时分组然后通过车牌号和颜色去重
				BasicDBObject dbObject = new BasicDBObject();
				BasicDBObject groupHour = new BasicDBObject("$hour", "$alarmtime");
				dbObject.put("hour", groupHour);
				dbObject.put("biz_id", "$bizId");
				groupFields = new BasicDBObject();
				groupFields.put("_id", dbObject);
				group = new BasicDBObject("$group", groupFields);
				// 统计分组后的报警数
				groupField2 = new BasicDBObject("_id", "$_id.hour");
				groupField2.put("count", new BasicDBObject("$sum", 1));
				group2 = new BasicDBObject("$group", groupField2);
				// 排序
				Bson sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));
				// 先匹配后分组再统计
				bson.add(project); //共用一个project条件
				bson.add(match); // 共用一个match条件
				bson.add(group);
				bson.add(group2);
				bson.add(sort);

				List<HashMap<String, Object>> hoursList = new ArrayList<HashMap<String, Object>>();
				List<Object> hoursVehicle = MGTemplete.aggregate("egov", "alarm_info_realtime", bson);
				for (Object object : hoursVehicle) {
					if (object != null) {
						Map<String, Object> hours_vehicle = (Map<String, Object>) object;

						HashMap<String, Object> hoursMap = new HashMap<String, Object>();
						//时间转换
						int hour=Integer.valueOf(String.valueOf( hours_vehicle.get("_id")));
						if(Integer.valueOf(String.valueOf( hours_vehicle.get("_id")))+8 >= 24){
							hour=Integer.valueOf(String.valueOf( hours_vehicle.get("_id")))+8-24;
						}else{
							hour=Integer.valueOf(String.valueOf( hours_vehicle.get("_id")))+8;
						}
						hoursMap.put("hour",hour);
						hoursMap.put("count",hours_vehicle.get("count"));
						hoursList.add(hoursMap);
					}
				}
				res.put("hourList", hoursList);
				list.add(res);
			}
			result.put("code", 10001);
			result.put("data", list);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 10002);
			result.put("msg", "程序出错!");
		}
		return result;
	}
	

}
